package com.jingli.pile.demo;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jingli.pile.domain.KafkaPortStatus;
import com.jingli.pile.entity.*;
import com.jingli.pile.kafka.KafkaMessageConsumer;
import com.jingli.pile.service.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

@Component
@EnableScheduling
public class DemoSchedule {
    private Logger logger = LoggerFactory.getLogger(DemoSchedule.class);
    @Autowired
    private KafkaMessageConsumer kafkaMessageConsumer;
    @Autowired
    private SupConnectorInfoService connectorInfoService;
    @Autowired
    private SupStationStatsInfoService stationStatsInfoService;
    @Autowired
    private SupStationInfoService stationInfoService;
    @Autowired
    private SupEquipmentInfoService equipmentInfoService;
    @Autowired
    private PushRecordService pushRecordService;
    @Autowired
    private ChargingOrderService chargingOrderService;
    @Autowired
    private NextTimeService nextTimeService;


    //推送接口状态
    @Scheduled(fixedRate = 1000*55)
    public void sendPortStatus(){
        SupConnectorInfo supConnectorInfo = connectorInfoService.getById(new Random().nextInt(100));
        if (null==supConnectorInfo){
            return;
        }
        KafkaPortStatus portStatus = new KafkaPortStatus();
        portStatus.setPortId(supConnectorInfo.getConnectorId());
        portStatus.setPortStatus("1");
        try {
            kafkaMessageConsumer.pushPortStatus(JSONObject.toJSONString(portStatus));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
//
//    @Scheduled(fixedRate = 1000*15)
    public void stationStats(){
        List<SupStationInfo> stationInfos = stationInfoService.list();
        for (SupStationInfo stationInfo : stationInfos) {
            QueryWrapper<SupEquipmentInfo> equipmentInfoQueryWrapper = new QueryWrapper<>();
            equipmentInfoQueryWrapper.eq("station_id",stationInfo.getStationId());
            List<SupEquipmentInfo> supEquipmentInfos = equipmentInfoService.list(equipmentInfoQueryWrapper);
            if (supEquipmentInfos.isEmpty()){
                continue;
            }
            DateTime dateTime = DateUtil.offsetDay(new Date(), -1);
            String formatDateTime = DateUtil.formatDateTime(dateTime);
            DateTime beginOfDay = DateUtil.beginOfDay(dateTime);
            DateTime endOfDay = DateUtil.endOfDay(DateUtil.endOfDay(dateTime));
            SupStationStatsInfo supStationStatsInfo = new SupStationStatsInfo();
            supStationStatsInfo.setStationId(stationInfo.getStationId());
            supStationStatsInfo.setOperatorId(stationInfo.getOperatorId());
            supStationStatsInfo.setEquipmentOwnerId(stationInfo.getOperatorId());
            supStationStatsInfo.setStartTime(DateUtil.formatDateTime(beginOfDay));
            supStationStatsInfo.setEndTime(DateUtil.formatDateTime(endOfDay));
            supStationStatsInfo.setStationElectricity(RandomUtil.randomDouble(20,100));
            supStationStatsInfo.setStationTotalChargeTime(new Random().nextInt(100));
            supStationStatsInfo.setStationTotalWarningNum(new Random().nextInt(10));
            supStationStatsInfo.setDailyChargeEnergy(RandomUtil.randomDouble(20,100));
            supStationStatsInfo.setDailyOtherEnergy(RandomUtil.randomDouble(20,100));
            supStationStatsInfo.setDailySwapNum(0);
            supStationStatsInfo.setDailyChargeNum(new Random().nextInt(10));
            stationStatsInfoService.saveOrUpdate(supStationStatsInfo);
        }
    }


    //模拟订单数据
    @Scheduled(fixedRate = 1000*5)
    public void doSendOrder() throws Exception {
        QueryWrapper<NextTime> nextTimeQueryWrapper = new QueryWrapper<>();
        nextTimeQueryWrapper.last("limit 1");
        NextTime nextTime = nextTimeService.getOne(nextTimeQueryWrapper);
        logger.info("下次执行时间:{}",nextTime.getNextTime());
        int compare = DateUtil.compare(new Date(), nextTime.getNextTime());
        logger.info("比较结果:{}",compare);
        if (compare<0){
            return;
        }
        int randomInt = RandomUtil.randomInt(150, 260);
        logger.info("延时订单生成:{}",DateUtil.formatDateTime(new Date()));
        List<PushRecord> pushRecords = pushRecordService.list();
        List<String> orderIds = new ArrayList<>();
        for (PushRecord pushRecord : pushRecords) {
            orderIds.add(pushRecord.getPushId());
        }
        QueryWrapper<SupConnectorInfo> connectorInfoQueryWrapper = new QueryWrapper<>();
        connectorInfoQueryWrapper.last("ORDER BY RAND() limit 1");
        SupConnectorInfo supConnectorInfo = connectorInfoService.getOne(connectorInfoQueryWrapper);
        SupEquipmentInfo equipmentInfo = equipmentInfoService.getById(supConnectorInfo.getEquipmentId());
        QueryWrapper<ChargingOrder> orderQueryWrapper = new QueryWrapper<>();
        orderQueryWrapper.notIn("ordernumber",orderIds);
        orderQueryWrapper.last("limit 1");
        ChargingOrder chargingOrder = chargingOrderService.getOne(orderQueryWrapper);
        logger.info("准备处理的订单信息:{}",JSONObject.toJSONString(chargingOrder));
        Date realEndTime = chargingOrder.getRealEndTime();
        Date createtime = chargingOrder.getCreatetime();
        long between = DateUtil.between(realEndTime, createtime, DateUnit.MINUTE);
        chargingOrder.setRealEndTime(new Date());
        chargingOrder.setEndtime(DateUtil.formatDateTime(new Date()));
        chargingOrder.setCreatetime(DateUtil.offsetMinute(new Date(),-(int)between));
        chargingOrder.setStarttime(DateUtil.formatDateTime(DateUtil.offsetMinute(new Date(),-(int)between)));
        chargingOrder.setPayTime(new Date());
        chargingOrder.setParkid(equipmentInfo.getEquipmentid());
        chargingOrder.setParklockid(supConnectorInfo.getConnectorId());
        logger.info("转换结束后的订单信息:{}",JSONObject.toJSONString(chargingOrder));
        chargingOrderService.saveOrUpdate(chargingOrder);
        DateTime dateTime = DateUtil.offsetMinute(nextTime.getNextTime(), randomInt);
        nextTime.setNextTime(dateTime);
        nextTimeService.updateById(nextTime);
        KafkaPortStatus portStatus = new KafkaPortStatus();
        portStatus.setPortStatus("1");
        portStatus.setPortId(supConnectorInfo.getConnectorId());
        kafkaMessageConsumer.pushPortStatus(JSONObject.toJSONString(portStatus));
        kafkaMessageConsumer.consumeOrder(chargingOrder.getOrdernumber());
    }


    public static void main(String[] args) {
        DateTime dateTime = DateUtil.offsetDay(new Date(), 1);
        int compare = DateUtil.compare(dateTime, new Date());
        System.out.printf(compare+"");
    }
}
